package org.zhaya.sdk.constant;

import java.math.BigDecimal;
import java.math.RoundingMode;

public enum CalculatorOperatorEnum {

    LEFT("(", 0),

    RIGHT(")", 0),
    ADD("+", 1),
    REDUCE("-", 1),
    MULTI("*", 2),
    DIVIDE("/", 2),

    REMAINDER("%", 1),

    POW("^", 2);

    private final String operate;
    private final int priority;

    CalculatorOperatorEnum(String operate, int priority) {
        this.operate = operate;
        this.priority = priority;
    }

    public String getOperate() {
        return operate;
    }

    public int getPriority() {
        return priority;
    }

    public static CalculatorOperatorEnum convert(String operate)
            throws IllegalOperationException {
        switch (operate) {
            case "+":
                return ADD;
            case "-":
                return REDUCE;
            case "*":
                return MULTI;
            case "/":
                return DIVIDE;
            case "%":
                return REMAINDER;
            case "^":
                return POW;
            case "(":
                return LEFT;
            case ")":
                return RIGHT;
            default:
                throw new IllegalOperationException("illegal operator: " + operate);
        }
    }

    public static BigDecimal calculate(CalculatorOperatorEnum op, BigDecimal prev, BigDecimal cur)
            throws IllegalOperationException {
        switch (op) {
            case ADD:
                return prev.add(cur);
            case REDUCE:
                return prev.subtract(cur);
            case MULTI:
                return prev.multiply(cur);
            case DIVIDE:
                return prev.divide(cur,10, RoundingMode.HALF_UP);
            case REMAINDER:
                return prev.remainder(cur);
            case POW:
                return prev.pow(cur.intValue());
            default:
                throw new IllegalOperationException("illegal operator.");
        }
    }

    public static class IllegalOperationException extends Exception {

        public IllegalOperationException(String message) {
            super(message);
        }

    }
}


